/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package wetest;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;

/**
 *
 * @author trungdv2
 */
public class NioTest
{
   
    public static void main(String[] args) throws IOException{
        SocketChannel socketChannel = SocketChannel.open();        
        socketChannel.configureBlocking(false);
        
        Selector selector = Selector.open();
        socketChannel.register(selector, SelectionKey.OP_CONNECT | SelectionKey.OP_READ | SelectionKey.OP_WRITE);
        
        socketChannel.connect(new InetSocketAddress("localhost", 443));
        
        while (true){
            int readyChannels = selector.select();
            if (readyChannels == 0)
                continue;
            Set<SelectionKey> selectedKeys = selector.selectedKeys();
            Iterator<SelectionKey> keyIterator = selectedKeys.iterator();
            while (keyIterator.hasNext()){
                SelectionKey key = keyIterator.next();
                keyIterator.remove();
                if (!key.isValid())
                    continue;
                
                if (key.isConnectable()){
                    System.out.println("connectable");
                } else if (key.isReadable()){
                    System.out.println("readable");
                } else if (key.isWritable()){
                    
                }   
            }
        }
        
    }     
}
